package com.haoze.nurseapp.controller;

import com.alibaba.fastjson.JSON;
import com.haoze.common.response.Result;
import com.haoze.common.response.ResultGenerator;
import com.haoze.common.utils.UUIDUtil;
import com.haoze.nurseapp.dto.ResultDTO;
import com.haoze.nurseapp.dto.app.AppUpdateQueryDTO;
import com.haoze.nurseapp.dto.app.AppUpgradeAddDTO;
import com.haoze.nurseapp.enumeration.AppUpgradeTypeEnum;
import com.haoze.nurseapp.service.AppUpgradeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Collections;

/**
 * @author wangze
 * @date 2020-06-08 9:18.
 **/
@RestController
@RequestMapping("/nurseapp/app/upgrade")
@Api(value = "app更新", tags = "app更新")
public class AppUpgradeController {
	private static final Logger log = LoggerFactory.getLogger(AppUpgradeController.class);

	@Resource
	private AppUpgradeService appUpgradeService;

	@Value("${app.remoteUpUrl}")
	private String remoteUpUrl;

	@ApiOperation("检查app是否是最新版本")
	@GetMapping("/update")
	public Result update(@RequestParam String appid, @RequestParam String version) {
		AppUpdateQueryDTO queryDto = new AppUpdateQueryDTO();
		queryDto.setAppid(appid);
		queryDto.setVersion(version);
		return appUpgradeService.queryAppUpdateInfo(queryDto);
	}


	@ApiOperation("更新app包")
	@PostMapping("/addOrUpdate")
	public Result addOrUpdate(@RequestParam("file") MultipartFile file
			, @RequestParam String appid
			, @RequestParam String version
			, @RequestParam(required = false) String hospitalId
			, @RequestParam(required = false) String note
	) throws IOException, URISyntaxException {
		final String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
		File apkFile = File.createTempFile(UUIDUtil.randomString(),  "." + suffix);
		file.transferTo(apkFile);
		apkFile.setReadable(true, false);
		ResultDTO fileUploadResult = JSON.parseObject(this.remoteUpload(apkFile), ResultDTO.class);
		apkFile.delete();
		if (!fileUploadResult.getCode().equals(200)) {
			return ResultGenerator.genFailedResult(fileUploadResult.getMsg());
		}
		AppUpgradeAddDTO addDto = new AppUpgradeAddDTO();
		addDto.setAppid(appid);
		addDto.setVersion(version);
		addDto.setNote(note);
		addDto.setFilePath(String.valueOf(fileUploadResult.getData()));
		addDto.setHospitalId(hospitalId);
		appUpgradeService.addOrUpdateAppUpgrade(addDto);
		return ResultGenerator.genOkResult();

	}

	/**
	 * 远程上传到指定的 nginx 服务器
	 *
	 * @param file
	 * @return
	 * @throws IOException
	 * @throws URISyntaxException
	 */
	public String remoteUpload(File file) throws URISyntaxException, IOException {
		HttpHeaders headers = new HttpHeaders();
		headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));
		headers.setContentType(MediaType.MULTIPART_FORM_DATA);
		MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
		body.add("file", new FileSystemResource(file));
		body.add("folder", "apk");
		HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(body, headers);
		HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
		factory.setConnectionRequestTimeout(3000);
		factory.setConnectTimeout(5000);
		RestTemplate restTemplate = new RestTemplate(factory);
		ResponseEntity<String> response = restTemplate.exchange(remoteUpUrl, HttpMethod.POST, entity, String.class);
		return response.getBody();
	}
}
